package com.ftp.longdistance.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSONUtil;
import com.ftp.longdistance.bean.Ftp;
import com.ftp.longdistance.bean.vo.BtnVo;
import com.ftp.longdistance.bean.vo.FtpVo;
import com.ftp.longdistance.service.service.SaveJsonLocalhostService;
import com.ftp.longdistance.util.PathFileUtils;
import com.ftp.longdistance.util.PathUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author TanYongPeng
 * <p>
 *     操作json
 * </p>
 */
@Service
public class SaveJsonLocalhostServiceImpl implements SaveJsonLocalhostService {
    @Override
    public void addLoginObj(FtpVo ftpVo) {
        if (PathFileUtils.exists("login.json")) {
            addLoginObj(loginReadList(),ftpVo);
        }else {
            List<FtpVo> ftpVoList = new ArrayList<>();
            addLoginObj(ftpVoList,ftpVo);
        }
    }

    @Override
    public List<FtpVo> loginList() {
        if (PathFileUtils.exists("login.json")){
            return loginReadList();
        }
        return null;
    }

    @Override
    public void delLoginObj(String id) {
        List<FtpVo> ftpVos = loginList();
        ftpVos.removeIf(s -> s.getId().equals(id));
        new PathFileUtils<FtpVo>().write(ftpVos,"login.json");
    }

    @Override
    public void addBtnObj(BtnVo btnVo) {
        if (PathFileUtils.exists(btnVo.getId().split("and")[1]+".json")){
            addBtnObj(btnReadList(btnVo.getId().split("and")[1]),btnVo);
        }else {
            List<BtnVo> btnVoList = new ArrayList<>();
            addBtnObj(btnVoList,btnVo);
        }
    }

    @Override
    public List<BtnVo> btnList(String host) {
        if (PathFileUtils.exists(host+".json")){
            return btnReadList(host);
        }
        return null;
    }

    @Override
    public void delBtnObj(String host,String btnId) {
        List<BtnVo> btnVoList = btnList(host);
        btnVoList.removeIf(s -> s.getId().equals(btnId));
        new PathFileUtils<BtnVo>().write(btnVoList,host+".json");
    }

    public List<FtpVo> loginReadList(){
         return new PathFileUtils<FtpVo>().lists("login.json",FtpVo.class);
    }

    public void addLoginObj(List<FtpVo> ftpVoList, FtpVo ftpVo){
        new PathFileUtils<FtpVo>().write(ftpVoList,ftpVo,"login.json");
    }

    public List<BtnVo> btnReadList(String host){
        return new PathFileUtils<BtnVo>().lists(host+".json",BtnVo.class);
    }

    public void addBtnObj(List<BtnVo> btnVoList, BtnVo btnVo){
        new PathFileUtils<BtnVo>().write(btnVoList,btnVo,btnVo.getId().split("and")[1]+".json");
    }


}
